package com.example.springboot_sdse_air.service;

import com.example.springboot_sdse_air.entity.MinerUTaskResponse;
import com.example.springboot_sdse_air.entity.MinerUTaskStatusResponse;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能：
 * 作者：王彬 202200111149
 * 日期：2025-04-27 16:50
 */
@Service
public class MinerUService {
    private static final String API_TASK_URL = "https://mineru.net/api/v4/extract/task";
    private static final String API_TASK_STATUS_URL = "https://mineru.net/api/v4/extract/task/";
    private static final String TOKEN = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiIxMDIwOTY4MCIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc0OTcwNTk2MiwiY2xpZW50SWQiOiJsa3pkeDU3bnZ5MjJqa3BxOXgydyIsInBob25lIjoiMTUzODg0NjkzNjgiLCJvcGVuSWQiOm51bGwsInV1aWQiOiI2NzE4MzFmNy02OGY5LTQ0MDctOGQzNS1mOWVjNjIwNmY1ZWUiLCJlbWFpbCI6IiIsImV4cCI6MTc1MDkxNTU2Mn0.YR-VrjuDVlGMd5i2yugJDKF2_mBXMma29A5I9yzEKWH2yqF-tPODFpo8NoembOSYsRViyyXiZTi0BdEIhe2D6w";
    private static final int MAX_RETRIES = 30; // 最大重试次数
    private static final int RETRY_DELAY_MS = 2500; // 每次重试的延迟时间，单位：毫秒

    private final RestTemplate restTemplate;

    public MinerUService() {
        this.restTemplate = new RestTemplate();
    }

    // 第一步：提交任务，拿到 taskId
    public String submitTask(String fileUrl) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(TOKEN);

        // 设置请求体
        Map<String, Object> body = new HashMap<>();
        body.put("url", fileUrl);
        body.put("is_ocr", false);
        body.put("enable_formula", true);
        body.put("enable_table", true);
        body.put("language", "auto");

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        try {
            ResponseEntity<MinerUTaskResponse> response = restTemplate.postForEntity(
                    API_TASK_URL, requestEntity, MinerUTaskResponse.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null
                    && response.getBody().getCode() == 0 && response.getBody().getMsg().equals("ok")) {
                return response.getBody().getData().getTaskId();
            } else {
                throw new RuntimeException("调用 MinerU API 失败，响应状态码:" + response.getStatusCodeValue() +
                        "   接口状态码:" + response.getBody().getCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("调用 MinerU API 出错：" + e.getMessage(), e);
        }
    }

    // 第二步：轮询查询状态（GET方式）带最大重试次数
    public String waitForTaskDone(String taskId) throws InterruptedException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(TOKEN);

        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        String url = API_TASK_STATUS_URL + taskId;
        int retryCount = 0;

        while (retryCount < MAX_RETRIES) {
            retryCount++;
            ResponseEntity<MinerUTaskStatusResponse> response = restTemplate.exchange(
                    url, HttpMethod.GET, requestEntity, MinerUTaskStatusResponse.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null
                    && response.getBody().getCode() == 0 && response.getBody().getMsg().equals("ok")) {
                MinerUTaskStatusResponse result = response.getBody();
                String state = result.getData().getState();

                if ("done".equalsIgnoreCase(state)) {
                    return result.getData().getFullZipUrl(); // 解析完成，返回下载地址
                } else if ("failed".equalsIgnoreCase(state)) {
                    throw new RuntimeException("任务解析失败，错误信息：" + result.getData().getErrMsg());
                } else {
                    // 任务还在 pending / running / converting
                    Thread.sleep(RETRY_DELAY_MS); // 休眠2秒再查
                }
            } else {
                throw new RuntimeException("查询任务失败");
            }
        }
        // 如果超过最大重试次数，还没有完成，则抛出超时异常
        throw new RuntimeException("任务超时，超过最大重试次数！");
    }
}
